var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var CONFIG = require('../../config');


var YjxActUserReward = function (obj) {
    YjxBaseModel.call(this,obj);

    //`arr_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
    //`as_id` bigint(20) NOT NULL COMMENT '活动配置id',
    //`reward_amt` bigint(20) NOT NULL COMMENT '奖励数量',
    //`unit` varchar(20) NOT NULL COMMENT '奖励单位',
    //`min` bigint(20) NOT NULL COMMENT '奖励范围最小值',
    //`max` bigint(20) NOT NULL COMMENT '奖励范围最大值',
    //`state` int(3) NOT NULL DEFAULT '10' COMMENT '状态:10有效,20无效',
    //`desc` varchar(100) DEFAULT NULL COMMENT '备注',
    //`create_time` datetime NOT NULL,
    //`update_time` datetime NOT NULL,
    //`update_by` varchar(50) DEFAULT NULL,
    //`del_flg` int(1) NOT NULL DEFAULT '0',

};

YjxActUserReward.prototype = new YjxBaseModel();

// 取得表名
YjxActUserReward.prototype.getTableName = function(){
    return 'yjx_act_user_reward';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxActUserReward.prototype.getWhereConditionOfKeyEqual = function(){
    return 'aur_id='+this.aur_id;
};


/**
 * 获取用户有效的收益支出记录
 *
 * @author 李强
 * @date 2018-06-08
 *@param userId         用户唯一标识
 * @param callback
 */
YjxActUserReward.prototype.getUserBalance = function(userId,callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('YjxActUserReward.getUserBalance Err:'+err);
        }

        var sql = ' SELECT yaur.cur_reward AS balance ' +
            ' from yjx.yjx_act_user_reward yaur ' +
            ' WHERE yaur.user_id = ' + userId +
            ' AND yaur.del_flg = 0 ' +
            ' AND yaur.org_id = 0 ' +
            ' AND yaur.state=10 ' +
            ' ORDER BY yaur.aur_id desc LIMIT 1';

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            return callback(error, result);
        });
    });
};


/**
 * 获取用户总收益记录表
 *
 * @author 李强
 * @date 2018-06-08
 *@param userId         用户唯一标识
 * @param callback
 */
YjxActUserReward.prototype.getUserTotalReward = function(userId,callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('YjxActUserReward.getUserTotalReward Err:'+err);
        }

        var sql = ' SELECT SUM(yaur.bal_reward) AS totalReward ' +
            ' from yjx.yjx_act_user_reward yaur ' +
            ' WHERE yaur.bal_flg = 1 ' +
            ' AND yaur.user_id =' + userId +
            ' AND yaur.del_flg = 0 ' +
            ' AND yaur.r_type in (10,20,21,30,31,32) ' +
            ' AND yaur.org_id = 0 ' +
            ' AND yaur.state=10';

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            callback(error, result);
        });
    });
};


/**
 * 获取用户收益明细列表
 * @returns {string}
 */
function sql_getUserRewardList(bForCnt,userId,pageNum, pageSize) {

    var sql = '';
    if(bForCnt) {
        sql += " SELECT " +
             "   COUNT(res.id) AS `count` ";
    } else  {
        sql += "	SELECT	" +
               "	  res.*	" ;
    }
    sql +=  "	FROM	" +
        "	  (SELECT	" +
        "	    aur.aur_id AS id,	" +
        "	    aur.bal_flg AS `type`,	" +
        "	    aur.bal_reward AS balReward,	" +
        "	    aur.aup_id AS productId,	" +
        "	    DATE_FORMAT(	" +
        "	      aur.create_time,	" +
        "	      '%Y-%c-%d %H:%i:%s'	" +
        "	    ) AS `time`,	" +
        "	    UNIX_TIMESTAMP(aur.create_time) AS `timestamp`,	" +
        "	    ya.title AS activityName,	" +
        "	    aur.r_type  AS rType ,	" +
        "	CASE	" +
        "	    WHEN aur.r_type = 10	" +
        "	    THEN '获奖奖励'	" +
        "	    WHEN aur.r_type = 20	" +
        "	    THEN '邀请红包'	" +
        "	     WHEN aur.r_type = 21	" +
        "	    THEN '参与红包'	" +
        "	     WHEN aur.r_type = 30	" +
        "	    THEN '系统红包'	" +
        "	     WHEN aur.r_type = 31	" +
        "	    THEN '点赞红包'	" +
        "	     WHEN aur.r_type = 32	" +
        "	    THEN '获赞红包'	" +
        "	    ELSE ''	" +
        "	  END AS `title` " +
        "	  FROM	" +
        "	    yjx.yjx_act_user_reward aur,	" +
        "	    yjx.yjx_activity ya	" +
        "	  WHERE aur.bal_flg = 1	" +
        "	    AND aur.act_id = ya.act_id	" +
        "	    AND aur.del_flg = 0	" +
        "	    AND aur.r_type in (10,20,21,30,31,32)	" +
        "	    AND aur.org_id = 0	" +
        "	    AND ya.del_flg = 0	" +
        "	    AND aur.user_id = "+userId+"	" +
        "	  UNION	" +
        "	  ALL	" +
        "	  SELECT	" +
        "	    aur.aur_id AS id,	" +
        "	    aur.bal_flg AS `type`,	" +
        "	    aur.bal_reward AS balReward,	" +
        "	    aur.aup_id AS productId,	" +
        "	    DATE_FORMAT(	" +
        "	      aur.create_time,	" +
        "	      '%Y-%c-%d %H:%i:%s'	" +
        "	    ) AS `time`,	" +
        "	    UNIX_TIMESTAMP(aur.create_time) AS `timestamp`,	" +
        "	    '' AS activityName,	" +
        "	    0  AS rType	, " +
        "	    '提现'  AS `title`	 " +
        "	  FROM	" +
        "	    yjx.yjx_act_finance_his afh,	" +
        "	    yjx.yjx_act_user_reward aur	" +
        "	  WHERE aur.user_id = "+userId+"	" +
        "	    AND afh.user_id = "+userId+"	" +
        "	    AND aur.bal_flg = 2	" +
        "	    AND afh.cash_state = 20	" +
        "	    AND aur.del_flg = 0	" +
//        "	    AND aur.r_type in (10,20,21)	" +
        "	    AND aur.org_id = 0	" +
        "	    AND afh.del_flg = 0	" +
        "	    AND afh.aur_id = aur.aur_id) res	" +
        "	    ORDER BY res.time DESC	" ;
    if (!bForCnt) {
        if (typeof pageNum !== 'undefined' && pageNum !== null &&
            typeof pageSize !== 'undefined' && pageSize !== null)
        {
            var skipCnt = Number(pageNum||'0') * Number(pageSize||'0');
            sql += " LIMIT " + skipCnt + "," + Number(pageSize||'0');
        }
    }
    return sql;
}


/**
 * 获取用户收益列表
 *
 * @author 毛凯
 * @date 2017-11-17
 *
 * @param userId  用户id
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param callback 回调
 *           err: 查询失败
 *           results: 活动列表
 *
 * */
YjxActUserReward.prototype.getUserRewardList = function (userId,pageNum, pageSize,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxActivityModel.js [getActivityList] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getUserRewardList(false,userId,pageNum, pageSize);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxActivityModel.js [getActivityList] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    })
};
/**
 * 获取用户收益列表数量
 *
 * @author 毛凯
 * @date 2017-11-17
 *
 * @param userId  用户id
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param callback 回调
 *           err: 查询失败
 *           results: 活动列表
 *
 * */
YjxActUserReward.prototype.getUserRewardListCnt = function (userId,pageNum, pageSize,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxActivityModel.js [getActivityListCnt] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getUserRewardList(true,userId,pageNum, pageSize);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxActivityModel.js [getActivityListCnt] queryErr' + queryErr)
            }
            return callback(queryErr, results[0].count);
        });
    })
};


/**
 * 发放收益
 *
 * @author mk
 * @date 2018-06-12
 *
 * @param activityId 活动id
 * @param aupId   作品 id
 * @param userId 用户id
 * @param orgId 组织id
 * @param {Function} callback 回调
 */
YjxActUserReward.prototype.addRewardInfoFromUserProductInfo = function (activityId,aupId,userId,orgId, callback) {

    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxActUserProductModel.getActivityProductIds getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql ="	INSERT INTO yjx.yjx_act_user_reward (	" +
                "	  r_type,	" +
                "	  user_id,	" +
                "	  org_id,	" +
                "	  act_id,	" +
                "	  aup_id,	" +
                "	  bal_flg,	" +
                "	  bal_reward,	" +
                "	  cur_reward,	" +
                "	  state,	" +
                "	  create_time,	" +
                "	  update_time,	" +
                "	  del_flg	" +
                "	)	" +
                "	SELECT	" +
                "	  10 AS r_type,	" +
                "	  yaup.user_id,	" +
                "	  yaup.org_id,	" +
                "	  yaup.act_id,	" +
                "	  yaup.aup_id,	" +
                "	  1 AS bal_flg,	" +
                "	  yaup.reward_amt,	" +
                "	  yaup.reward_amt +	" +
                "	  IFNULL((SELECT	" +
                "	    yaur.cur_reward	" +
                "	  FROM	" +
                "	    yjx.yjx_act_user_reward yaur	" +
                "	  WHERE yaur.del_flg = 0 " ;
            if(orgId >0 && userId > 0){
                sql += " AND yaur.org_id = "+orgId ;
            }

            if(orgId<= 0 && userId && userId>0){
                sql += " AND yaur.user_id = "+userId+
                       " AND yaur.org_id = 0 " ;
            }
            sql+= "	  AND yaur.state = 10	" +
                "	  ORDER BY yaur.aur_id DESC	" +
                "	  LIMIT 0, 1),0) AS cur_reward,	" +
                "	  10 AS state,	" +
                "	  NOW(),	" +
                "	  NOW(),	" +
                "	  yaup.del_flg	" +
                "	FROM	" +
                "	  yjx.yjx_act_user_product yaup	" +
                "	WHERE  NOT EXISTS  	" +
                "	(SELECT	" +
                "	    *	" +
                "	  FROM	" +
                "	    yjx.yjx_act_user_reward yaur	" +
                "	  WHERE yaur.aup_id = yaup.aup_id AND yaur.del_flg = 0 AND yaur.r_type = 10 )	" +
                "	  AND yaup.act_id = "+activityId+"	" +
                "	  AND yaup.reward_amt > 0	" +
                "	  AND yaup.state = 30	" +
                "	  AND yaup.del_flg = 0	" +
                "	  AND yaup.aup_id = "+aupId+"	" ;
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxActUserProductModel.addRewardInfoFromUserProductInfo Err: ' + error);
            }
            return callback(error, results);
        })
    })
};


/**
 * 发放用户使用推广码的奖励
 *
 * @author 王俊
 * @date 2018-07-10
 *
 * @param options  参数对象
 * @param options.act_id   该笔奖励对应的活动 id
 * @param options.user_id  该笔奖励对应的用户 id
 * @param options.org_id  该笔奖励对应的用户的组织 id
 * @param options.valid_aup_id 该笔奖励对应的作品 id
 * @param options.reward_amount 该笔奖励对应的作品 id
 * @param callback
 *             error
 */
YjxActUserReward.prototype.distributeUserUsePromoterCodeIncome= function (options, callback) {
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxActUserReward.js [distributeUserUsePromoterCodeIncome] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql =
            ' INSERT INTO yjx.yjx_act_user_reward (r_type, user_id, org_id, act_id, aup_id, bal_flg, bal_reward, cur_reward, STATE, create_time, update_time) ' +
            ' SELECT 21 AS r_type, ' + // 使用推荐码奖励
            '        yaup.user_id, ' +
            '        yaup.org_id, ' +
            '        yaup.act_id, ' +
            '        yaup.aup_id, ' +
            '        1 AS bal_flg, ' +
            '        '+options.reward_amount+' AS reward_amt, ' +
            '        '+options.reward_amount+' + IFNULL( ' +
            '                       (SELECT yaur.cur_reward ' +
            '                        FROM yjx.yjx_act_user_reward yaur ' +
            '                        WHERE yaur.del_flg = 0 ' +
            '                          AND yaur.org_id = 0 ' +
            '                          AND yaur.user_id = ' + options.user_id +
            '                          AND yaur.state = 10 ' +
            '                        ORDER BY yaur.aur_id DESC LIMIT 0, 1), 0) AS cur_reward, ' +
            '        10 AS STATE, ' +
            '        NOW(), ' +
            '        NOW() ' +
            ' FROM yjx.yjx_act_user_product yaup ' +
            ' WHERE yaup.del_flg = 0 ' +
            '   AND yaup.aup_id = ' + options.valid_aup_id +
            '   AND NOT EXISTS (SELECT * FROM yjx.yjx_act_user_reward yaur WHERE yaur.aup_id = yaup.aup_id and yaur.r_type = 21 AND yaur.del_flg = 0) ' +
            '   AND yaup.user_id = ' + options.user_id;
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxActUserReward.js [distributeUserUsePromoterCodeIncome] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    })
};

/**
 * 组织参加活动信息统计
 * @param orgId 组织id
 * @param callback
 */
YjxActUserReward.prototype.getOrgActStatsInfo= function (orgId, callback) {
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxActUserReward.js [getOrgActStatsInfo] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql =
            ' SELECT SUM(x.reward) AS reward, SUM(x.actCnt) AS actCnt '+
            ' 	,SUM(x.prodCnt) AS prodCnt, SUM(x.userCnt) AS userCnt '+
            ' FROM ( '+
            ' 	SELECT SUM(aur.bal_reward) AS reward, 0 AS actCnt, 0 AS prodCnt, 0 AS userCnt '+
            ' 	FROM yjx.yjx_act_user_reward aur '+
            ' 	WHERE aur.del_flg=0 '+
            ' 	AND aur.state=10 '+// 有效
            ' 	AND aur.bal_flg=1 '+// 奖励
            ' 	AND aur.org_id='+orgId+
            ' 		UNION ALL '+
            ' 	SELECT 0 AS reward, COUNT(DISTINCT aup.act_id) AS actCnt, 0 AS prodCnt, 0 AS userCnt '+
            ' 	FROM yjx.yjx_act_user_product aup '+
            ' 	WHERE aup.del_flg=0 '+
            ' 	AND aup.state=30 '+// 审核通过作品
            ' 	AND aup.org_id='+orgId+
            ' 		UNION ALL '+
            ' 	SELECT 0 AS reward, 0 AS actCnt, COUNT(aup.aup_id) AS prodCnt, 0 AS userCnt '+
            ' 	FROM yjx.yjx_act_user_product aup '+
            ' 	WHERE aup.del_flg=0 '+
            ' 	AND aup.state=30 '+// 审核通过作品
            ' 	AND aup.org_id='+orgId+
            ' 		UNION ALL '+
            ' 	SELECT 0 AS reward, 0 AS actCnt, 0 AS prodCnt, COUNT(DISTINCT r.user_id) AS userCnt '+
            ' 	FROM yjx.yjx_org_r r '+
            ' 	WHERE r.del_flg=0 '+
            ' 	AND r.state=10 '+// 有效成员
            ' 	AND r.org_id='+orgId+
            ' ) x ';
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxActUserReward.js [getOrgActStatsInfo] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    })
};

/**
 * 获取个人用户作为推广方的总奖励
 *
 * @author 王俊
 * @date 2017-07-19
 *
 * @param userId        用户唯一标识
 * @param callback
 *          error
 *          total
 */
YjxActUserReward.prototype.getUserPromoterTotalReward = function (userId, callback) {
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxActUserReward.js [getUserPromoterTotalReward] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql =
            ' SELECT sum(yaur.bal_reward) AS totalReward ' +
            ' FROM yjx.yjx_act_user_reward yaur ' +
            ' WHERE yaur.r_type = 20 ' + // 标记推广奖励
            '   AND yaur.org_id=0 ' +    // 只查询个人
            '   AND yaur.user_id= ' + userId +
            '   AND yaur.state=10 ' +    // 有效值
            '   AND yaur.del_flg=0 ' ;
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr || !results || results.length <=0) {
                console.log('YjxActUserReward.js [getUserPromoterTotalReward] queryErr' + queryErr);
                return callback(queryErr || '计算收益失败', 0);
            }
            return callback(queryErr, Number(results[0].totalReward) || 0);
        });
    })
};

/**
 * 发放推荐码拥有者收益
 *
 * @author mk
 * @date 2018-07-19
 *
 * @param options  参数对象
 * @param options.act_id   该笔奖励对应的活动 id
 * @param options.user_id  该笔奖励对应作品的用户 id
 * @param options.uid      该笔奖励对应的用户 id
 * @param options.org_id  该笔奖励对应的用户的组织 id
 * @param options.valid_aup_id 该笔奖励对应的作品 id
 * @param options.reward_amount 该笔奖励对应的作品 id
 * @param {Function} callback 回调
 */
YjxActUserReward.prototype.distributeOwnCcodeWithProducts = function (options, callback) {

    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxActUserProductModel.getActivityProductIds getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql ="	INSERT INTO yjx.yjx_act_user_reward (	" +
            "	  r_type,	" +
            "	  user_id,	" +
            "	  org_id,	" +
            "	  act_id,	" +
            "	  aup_id,	" +
            "	  bal_flg,	" +
            "	  bal_reward,	" +
            "	  cur_reward,	" +
            "	  state,	" +
            "	  create_time,	" +
            "	  update_time,	" +
            "	  del_flg	" +
            "	)	" +
            "	SELECT	" +
            "	  20 AS r_type,	" +
            "	  "+options.uid +"  AS user_id,	" +
            "	  yaup.org_id,	" +
            "	  yaup.act_id,	" +
            "	  yaup.aup_id,	" +
            "	  1 AS bal_flg,	" +
            "	  "+options.reward_amount+" AS bal_reward,	" +
            "	 "+options.reward_amount+" + " +
            "	  IFNULL((SELECT	" +
            "	    yaur.cur_reward	" +
            "	  FROM	" +
            "	    yjx.yjx_act_user_reward yaur	" +
            "	  WHERE yaur.del_flg = 0 " ;
        if(options.org_id >0 && options.uid > 0){
            sql += " AND yaur.org_id = "+options.org_id ;
        }

        if(options.org_id <= 0 && options.uid && options.uid > 0){
            sql += " AND yaur.user_id = "+options.uid+
                " AND yaur.org_id = 0 " ;
        }
        sql+= "	  AND yaur.state = 10	" +
            "	  ORDER BY yaur.aur_id DESC	" +
            "	  LIMIT 0, 1),0) AS cur_reward,	" +
            "	  10 AS state,	" +
            "	  NOW(),	" +
            "	  NOW(),	" +
            "	  yaup.del_flg	" +
            "	FROM	" +
            "	  yjx.yjx_act_user_product yaup	" +
            "	WHERE  NOT EXISTS  	" +
            "	(SELECT	" +
            "	    *	" +
            "	  FROM	" +
            "	    yjx.yjx_act_user_reward yaur	" +
            "	  WHERE yaur.aup_id = yaup.aup_id AND yaur.del_flg = 0 AND yaur.r_type = 20 )	" +
            "	  AND yaup.act_id = "+options.act_id+"	" +
            "	  AND yaup.state = 30	" +
            "	  AND yaup.del_flg = 0	" +
            "	  AND yaup.aup_id = "+options.valid_aup_id+"	" ;
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxActUserProductModel.addRewardInfoFromUserProductInfo Err: ' + error);
            }
            return callback(error, results);
        })
    })
};



/**
 * 获取用户被推荐奖励列表_sql
 *
 * @param bForCnt  标记
 * @param options  参数对象
 * @param options.userId        用户id
 * @param options.code         用户私有码
 * @param options.pageNum       页码
 * @param options.pageSize      页容量
 * @param options.withTotalPage 是否需要总页数
 * @returns {string}
 */
function sql_getUserOwnCodeRewardList(bForCnt,options) {

    var sql = '';
    if(bForCnt) {
        sql += " SELECT " +
            "   COUNT(0) AS `count` ";
    } else  {
        sql += "	SELECT	" +
            "	  IFNULL(ytpu.nickname,'') AS `name`,	" +
            "	  yaur.bal_reward AS promoterReward,	" +
            "     IFNULL(ytpu.profile_photo,'http://itbour-back.oss-cn-hangzhou.aliyuncs.com/image/U13396/2017/12/15/181805976_wapZT7TnmRu3VV3Sm1MY') AS profilePhoto ," +
            "	  UNIX_TIMESTAMP(yaur.create_time) AS TIMESTAMP,	" +
            "	  yaur.create_time	" ;
    }
    sql +="	FROM	" +
            "	  yjx.yjx_act_user_reward yaur,	" +
            "	  yjx.yjx_act_user_product yaup	" +
            "	  LEFT JOIN yjx.yjx_third_party_user ytpu	" +
            "	    ON yaup.user_id = ytpu.user_id	" +
            "	    AND ytpu.del_flg = 0	" +
            "	    AND (	" +
            "	      ytpu.account_type BETWEEN 200	" +
            "	      AND 300	" +
            "	    )	" +
            "	WHERE yaur.del_flg = 0	" +
            "	  AND yaup.del_flg = 0	" +
            "	  AND yaur.r_type = 20	" +
            "	  AND yaur.aup_id = yaup.aup_id	" +
            "	  AND yaup.state = 30	" +
            "	  AND yaup.c_code = '"+options.code+"'	" +
            "	  ORDER BY yaur.create_time DESC	" ;
    if (!bForCnt) {
        if (typeof options.pageNum !== 'undefined' && options.pageNum !== null &&
            typeof options.pageSize !== 'undefined' && options.pageSize !== null)
        {
            var skipCnt = Number(options.pageNum||'0') * Number(options.pageSize||'0');
            sql += " LIMIT " + skipCnt + "," + Number(options.pageSize||'0');
        }
    }
    return sql;
}


/**
 * 获取用户被推荐奖励列表
 *
 * @author mk
 * @date 2018-07-19
 *
 * @param options  参数对象
 * @param options.userId        用户id
 * @param options.code         用户私有码
 * @param options.pageNum       页码
 * @param options.pageSize      页容量
 * @param options.withTotalPage 是否需要总页数
 * @param {Function} callback 回调
 */
YjxActUserReward.prototype.getUserOwnCodeRewardList = function (options, callback) {

    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxActUserProductModel.getActivityProductIds getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql =sql_getUserOwnCodeRewardList(false,options);
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxActUserProductModel.addRewardInfoFromUserProductInfo Err: ' + error);
            }
            return callback(error, results);
        })
    })
};


/**
 * 获取用户被推荐奖励列表数量
 *
 * @author mk
 * @date 2018-07-19
 *
 * @param options  参数对象
 * @param options.userId        用户id
 * @param options.code         用户私有码
 * @param options.pageNum       页码
 * @param options.pageSize      页容量
 * @param options.withTotalPage 是否需要总页数
 * @param {Function} callback 回调
 */
YjxActUserReward.prototype.getUserOwnCodeRewardCnt = function (options, callback) {

    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxActUserProductModel.getActivityProductIds getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql = sql_getUserOwnCodeRewardList(true,options);
            console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxActUserProductModel.addRewardInfoFromUserProductInfo Err: ' + error);
            }
            if (!results || results.length<=0){
                return callback(null,0);
            } else{
                return callback(error, results[0].count);
            }
        });
    })
};



/**
 * 调用存储过程存储奖励和user_like表
 *
 * @author mk
 * @date 2018-07-19
 *
 * @param {{Object}} options 请求参数
 * @param {Number} options.device               设备标识
 * @param {Number} options.userId               用户id
 * @param {Number} options.productId            作品 id
 * @param {Number} options.actId                活动 id
 * @param {Number}options.likeReward       点赞奖励
 * @param {Number}options.praisedReward     被点赞奖励
 * @param {Function} callback 回调
 */
YjxActUserReward.prototype.updateUserLikeReward = function (options, callback) {

    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxActUserProductModel.getActivityProductIds getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql = "call proc_update_user_like_reward(" + options.userId +" ," + options.productId +" , " + options.actId + " , " + options.likeReward + " , " + options.praisedReward +", @p_result" + ")";
        console.log(sql);
        connection.query(sql, function (error, result) {
            connection.release();
            if(error) {
                console.log(error);
                return callback(null, 2);
            }

            if(!result || result.length==0 || result[0].length==0 || !(result[0][0].hasOwnProperty("p_result"))){
                return callback(null,1);
            }
            var p_result = result[0][0].p_result;
            return callback(null,p_result);
        });
    })
};




/**
 * 检测用户获取的随机红包奖励
 *
 * @author mk
 * @date 2018-07-19
 *
 * @param options  参数对象
 * @param {Number} options.device               设备标识
 * @param {Number} options.userId               用户id
 * @param {Number} options.actId                活动 id
 * @param {Function} callback 回调
 */
YjxActUserReward.prototype.checkUserRandomRedPackage = function (options, callback) {

    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxActUserProductModel.getActivityProductIds getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql = "	SELECT	" +
            "	  COUNT(0) AS `count`	" +
            "	FROM	" +
            "	  yjx.yjx_act_user_reward yaur	" +
            "	WHERE yaur.del_flg = 0	" +
            "	AND yaur.r_type = 30	" +
            "	AND yaur.act_id = "+options.actId+"	" +
            "	AND yaur.user_id = "+options.userId+"	" ;
            console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxActUserProductModel.addRewardInfoFromUserProductInfo Err: ' + error);
            }
            if (!results || results.length<=0){
                return callback(null,0);
            } else{
                return callback(error, results[0].count);
            }
        });
    })
};


/**
 * 发放用户随机奖励红包
 *
 * @author mk
 * @date 2018-07-19
 *
 * @param options  参数对象
 * @param {Number} options.device               设备标识
 * @param {Number} options.userId               用户id
 * @param {Number} options.actId                活动 id
 * @param {Number}options.RandomRedReward         点赞奖励
 * @param {Number}options.curReward         当前余额
 * @param {Function} callback 回调
 */
YjxActUserReward.prototype.addUserRandomRedPackage = function (options, callback) {

    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxActUserProductModel.getActivityProductIds getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var cur_reward = options.RandomRedReward + options.curReward;
        var sql ="	INSERT INTO yjx.yjx_act_user_reward (	" +
                "	  r_type,	" +
                "	  user_id,	" +
                "	  org_id,	" +
                "	  act_id,	" +
                "	  aup_id,	" +
                "	  like_id,	" +
                "	  bal_flg,	" +
                "	  bal_reward,	" +
                "	  cur_reward,	" +
                "	  state,	" +
                "	  create_time,	" +
                "	  update_time,	" +
                "	  update_by	" +
                "	)	" +
                "	SELECT 	" +
                "	    30,	" +
                "	    "+options.userId+",	" +
                "	    0,	" +
                "	    "+options.actId+",	" +
                "	    0,	" +
                "	    0,	" +
                "	    1,	" +
                "	    "+options.RandomRedReward+",	" +
                "	    "+cur_reward+",	" +
                "	    10,	" +
                "	    NOW(),	" +
                "	    NOW(),	" +
                "	    "+options.userId+"	" +
                "	  FROM DUAL	" +
                "	  WHERE NOT EXISTS	" +
                "	   (SELECT	" +
                "	    *	" +
                "	  FROM	" +
                "	    yjx.yjx_act_user_reward yar	" +
                "	  WHERE yar.act_id = "+options.actId+"	" +
                "	    AND yar.user_id = "+options.userId+"	" +
                "	    AND yar.del_flg = 0	" +
                "	    AND yar.r_type = 30)	" ;
            console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxActUserProductModel.addRewardInfoFromUserProductInfo Err: ' + error);
            }
            return callback(error, results);
        });
    })
};




module.exports = YjxActUserReward;

